from django.conf import settings
from django.contrib.gis.db.models import GeoQ
from django.contrib.gis.geos import *
from django.contrib.gis.measure import D
from django.contrib.flatpages.models import FlatPage
from django.core import serializers
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext

from groundtruth.location.models import Location, LocationCluster, LocationComment, LocationType, Photo
from groundtruth.map.utils import *
from groundtruth.map.forms import GeocodeForm, KeywordForm, PhotoUploadForm

import sys

def index(request):
    fp = FlatPage.objects.get(url='/index/')
    geocode_form = GeocodeForm()
    keyword_form = KeywordForm()
    return render_to_response('geocode.html', {'fp': fp, 'form': geocode_form, 'keywordform': keyword_form}, context_instance=RequestContext(request))

def showMap(request):
    lat = request.GET.get('lat')
    lng = request.GET.get('lng')
    q = request.GET.get('q')
    map_center = lat + ', ' + lng
    layers = request.GET.getlist('layers')
    radius = request.GET.get('radius')
    radius_zoom = {
        '5': 12,
        '15': 11,
        '25': 10,
        '50': 9,
        '100': 8,
        '250': 7,
        '500': 6,
    }
    map_zoom = radius_zoom.get(radius)
    center = fromstr('POINT(%s %s)' % (lng, lat), srid=4326)
    #query = (GeoQ(coordinates__distance_lte=(center, D(mi=eval(radius)))) & GeoQ(type__in=layers))
    #geocode_results = Location.objects.filter(query).distance(center).order_by('distance')
    #for location in geocode_results:
    #    location.distance = location.distance * 0.000621371192
    return render_to_response('map/map.html', {'map_center': map_center, 'map_zoom': map_zoom, 'layers': layers, 'q': q}, context_instance=RequestContext(request))

def locationsXml(request):
    bounds = request.GET.get('b').split(',')
    zoom = int(request.GET.get('z'))
    offset = settings.CLUSTER_ZOOM_OFFSET.get(zoom)
    if offset == None:
        offset = 0
    zoom += offset
    swTiles = getTileFromCoords(float(bounds[0]), float(bounds[1]), zoom)
    neTiles = getTileFromCoords(float(bounds[2]), float(bounds[3]), zoom)
    layers = request.GET.get('layers')
    
    locations = Location.locations.clustered(zoom, swTiles, neTiles, layers)
    data = serializers.serialize("json", locations, fields="name, coordinates, point_count")
    
    return HttpResponse(data, mimetype="text/plain", )

def locationsXmlTest(request):
    bounds = request.GET.get('b').split(',')
    zoom = int(request.GET.get('z'))
    swTiles = getTileFromCoords(float(bounds[0]), float(bounds[1]), zoom)
    neTiles = getTileFromCoords(float(bounds[2]), float(bounds[3]), zoom)
    
    #locations = Location.locations.clustered(zoom, swTiles, neTiles)
    #data = serializers.serialize("json", locations, fields="name, coordinates, point_count")

    output = 'bounds: ' + bounds[0] + ',' + bounds[0] + '\n'
    output += 'zoom: ' + str(zoom) + '\n'
    output += 'swTiles: ' + str(swTiles[0]) + ',' + str(swTiles[1]) + '\n'
    output += 'neTiles: ' + str(neTiles[0]) + ',' + str(neTiles[1]) + '\n'
    
    return HttpResponse(output, mimetype="text/plain", )
    
def locationDetail(request, location_id, template):
    loc = None
    
    #parentLoc = get_object_or_404(Location, pk=locationId)
    parentLoc = Location.objects.get(id=location_id)
    if parentLoc.type.internal_code == "mine":
        loc = parentLoc.mine
    if parentLoc.type.internal_code == 'quarry':
        loc = parentLoc.quarry
    
    return render_to_response(template, {'location': loc}, context_instance=RequestContext(request))

def locationInfoWindow(request, location_id):
    loc = None
    
    #parentLoc = get_object_or_404(Location, pk=locationId)
    parentLoc = Location.objects.get(id=location_id)
    if parentLoc.type.internal_code == "mine":
        loc = parentLoc.mine
    if parentLoc.type.internal_code == 'quarry':
        loc = parentLoc.quarry
    
    return render_to_response(template, {'location': loc}, context_instance=RequestContext(request))

def locationPhotos(request, location_id, template):
    location = Location.objects.get(id=location_id)
    sys.stderr.write('location_id: ' + location_id + '\n')
    if request.method == 'POST':
        photo = Photo(location=location)
        upload_form = PhotoUploadForm(request.POST, request.FILES, instance=photo)
        if upload_form.is_valid():
            #photo = upload_form.save(commit=False)
            #photo.location = location
            upload_form.save()
            #location.photos_count = location.photos_count + 1
            #location.save()
    else:
        upload_form = PhotoUploadForm()

    photos = []
    if location.photos_count > 0:
        photos = location.get_photos()
    return render_to_response(template, {'photos': photos, 'upload_form': upload_form, 'flickr_user_id': settings.FLICKR_USER_ID}, context_instance=RequestContext(request))

def locationDiscussion(request, location_id, template):
    comments = LocationComment.objects.filter(location=location_id)
    return render_to_response(template, {'comments': comments, 'location_id': location_id}, context_instance=RequestContext(request))

def newComment(request, location_id, template):
    comment = LocationComment()
    comment.comment = request.POST.get('comment')
    location = Location.objects.get(id=location_id)
    comment.location = location
    comment.user = request.user
    comment.save()
    return render_to_response(template, {'comment': comment, 'location_id': location_id}, context_instance=RequestContext(request))

